<!DOCTYPE html>
<html lang="ch-CN">
<head>
  <meta charset="UTF-8">
  <title>事件的绑定</title>
</head>
<style>
  body {
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
  }

  #container {
    width: 800px;
    height: 500px;
    background-color: wheat;
    font-size: 30px;
    /*文本透明*/
    /*text-decoration: none;*/
    font-family: "华文楷体";
    position: relative;
  }

  #box1 {
    width: 100px;
    height: 100px;
    background-color: #b3b1af;
    border: solid 1px black;
    text-align: center;
    float: left;
  }

  #box2 {
    width: 100px;
    height: 100px;
    background-color: #b3b1af;
    border: solid 1px black;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    /*margin-left: 45%;*/
    /*margin-top: 15%;*/
    text-align: center;
    /*margin: auto;*/

  }

</style>
<body>
<div id="container">
  <div id="box1">box1</div>
  <div id="box2">box2</div>
</div>

</body>
<script>
  var box1 = document.getElementById("box1")
  var box2 = document.getElementById("box2")
  var container = document.getElementById("container")

  function box_move(box) {
    let count =1
    box.onmousedown = function (event) {
      // 鼠标每次点击box时都向上1个单位——使移动的这个div永远覆盖在另一个div上
      box.style.zIndex = count
      count++
      // 计算指针在box中的位置
      let box_X = event.offsetX
      let box_Y = event.offsetY
      container.onmousemove = function (event) {
        if (event.pageY-box_Y<=-5||event.pageX-(container.offsetLeft+box_X)<=-5||
                //container盒子高度-box1盒子高度<=指针离顶端的高度-指针在container盒子的高度(即box不出下边界)
                container.clientHeight - box1.clientHeight <= event.pageY - (container.offsetTop + box_Y)||
                //container盒子宽度-box1盒子宽度<=指针离左端的宽度-指针在container盒子的宽度(即box不出右边界)
                container.clientWidth - box1.clientWidth <= event.pageX-(container.offsetLeft + box_X)) {
          alert("请不要越界！！")
          // 重新加载页面
          location.reload();
        }
        box.style.position = "absolute"
        // 如果CSS中写了margin这里必须清除(margin如果是auto就不需要清除),不然box移动后系统会默认加上CSS中的margin
        // box.style.marginTop = "0"
        // box.style.marginLeft = "0"
        // 如果CSS中写了translate这里必须清除，不然box移动后系统会默认加上CSS中的translate
        box.style.transform = "translate(0,0)"
        // event.pageX指针相对于整个文档页面（或浏览器窗口）的水平位置（即鼠标指针的X坐标）
        // container.offsetLeft——container盒子相对于父元素的水平距离
        box.style.left = event.pageX-(container.offsetLeft + box_X) + "px";
        box.style.top = event.pageY - (container.offsetTop + box_Y) + "px";
      }
      container.onmouseup = function () {
        container.onmousemove = null
        container.onmouseup = null
      }
      //当拖动内容或者ctrl-A时  功能会出现异常，通过return false取消默认行为
      return false
    }
  }

  box_move(box1)
  box_move(box2)
</script>
</html>